* Generate lagged CDS spreads
gen lag_cds_spread = L.cds if _n > 1
bysort firm (trend): replace lag_cds_spread = L.cds

* Calculate CDS returns (percentage change in spreads)
gen cds_return1 = (cds - lag_cds_spread) / lag_cds_spread

* Run the predictive regression
reg cds_return jumps vix leverage term i.firm i.trend

* Save fitted values (predicted CDS returns)
predict fitted_cds_return

* Calculate predicted CDS spreads
gen predicted_cds_spread = lag_cds_spread * (1 + fitted_cds_return)

* Deviations between observed and predicted CDS spreads
gen deviation = predicted_cds_spread - cds

* Summary statistics for deviations
summ deviation

* Plot deviations over time for a specific firm
tsset firm trend
gen firm_filter = (firm == 1 )  // Filter for firm_id = 1
twoway line deviation trend if firm_filter, title("Deviations for Firm 1") ///
    xtitle("Date") ytitle("Deviation")

* ---- Robsuteness Checks --------
* Include squared terms for nonlinear effects 
gen cds_jump_sq = jumps^2
gen vix_sq = vix^2
reg cds_return jumps cds_jump_sq vix vix_sq leverage term i.firm i.trend
predict fitted_cds_return_nonlinear
gen predicted_cds_spread_nonlinear = lag_cds_spread * (1 + fitted_cds_return_nonlinear)
gen deviation_nonlinear = predicted_cds_spread_nonlinear - cds

* Run fixed-effects panel regression
xtset firm trend
xtreg cds_return jumps vix leverage term, fe
predict fitted_cds_return_fe
gen predicted_cds_spread_fe = lag_cds_spread * (1 + fitted_cds_return_fe)
gen deviation_fe = predicted_cds_spread_fe - cds

* ------- Advanced Analysis ------------

reg volume deviation
* Panel VAR to test dynamic relationships
pvar deviation cds_return, lags(3)

* Test if deviations Granger-cause CDS returns
pvar deviation cds_return, lags(3)
vargranger

* Export regression output to a table
outreg2 using results.doc, replace ctitle("Predictive Regression")

* Save deviations to a new dataset
save deviations_data.dta, replace







